/*
 * Copyright (c) United Binary LLC.  All rights reserved.
 * 
 * This code is licensed under the MIT License
 * 
 * SEE: http://harnessit.codeplex.com/license
 * 
 */
#region using ...
using System;
using System.Text;
#endregion

namespace UnitedBinary.Core.Utility.Text
{
	/// <include file='Text.xml' path='/Docs/Format/Class/*'/>
	public sealed class Format
	{
		private Format() {}

		/// <include file='Text.xml' path='/Docs/Format/BytesToHexString/*'/>
		public static string BytesToHexString(byte[] source)
		{
			StringBuilder sb = new StringBuilder();
			for (int i=0; i < source.Length; i++)
			{
				sb.AppendFormat("{0:X2}", source[i]);
			}

			string hex = sb.ToString();
			return hex;
		}

		/// <include file='Text.xml' path='/Docs/Format/BytesToCommaSeparatedList/*'/>
		public static string BytesToCommaSeparatedList(byte[] source)
		{
			StringBuilder sb = new StringBuilder();
			for (int i=0; i < source.Length; i++)
			{
				sb.AppendFormat("{0}0x{1:X2}", (i == 0 ? "" : ", "), source[i]);
			}

			string list = sb.ToString();
			return list;
		}

		/// <include file='Text.xml' path='/Docs/Format/BytesToFormattedString/*'/>
		public static string BytesToFormattedString(string format, byte[] source)
		{
			StringBuilder sb = new StringBuilder();
			for (int i=0; i < source.Length; i++)
			{
				sb.AppendFormat(format, source[i]);
			}

			string text = sb.ToString();
			return text;
		}

		/// <include file='Text.xml' path='/Docs/Format/HexStringToBytes/*'/>
		public static byte[] HexStringToBytes(string source)
		{
			if (source.Length % 2 != 0)
			{
				throw new ArgumentException("Argument must be divisible by two.", "source");
			}

			byte[] bytes = new byte[source.Length/2];
			for (int i=0; i < bytes.Length; i++)
			{
				bytes[i] = Convert.ToByte(source.Substring(i * 2, 2), 16);
			}

			return bytes;
		}

		/// <include file='Text.xml' path='/Docs/Format/PadString/*'/>
		public static string PadString(string text, char padChar, int length, bool padFromFront)
		{
			if (length <= 0)
			{
				throw new ArgumentException("Length must be positive.", "length");
			}

			if (text == null)
			{
				text = string.Empty;
			}

			StringBuilder sb = new StringBuilder(length);
			if (padFromFront)
			{
				int currentLength = 0;
				int padsNeeded = length - text.Length;
				while (currentLength < padsNeeded)
				{
					currentLength++;
					sb.Append(padChar);
				}

				sb.Append(text);
			}
			else
			{
				sb.Append(text);

				int currentLength = text.Length;
				while (currentLength < length)
				{
					currentLength++;
					sb.Append(padChar);
				}
			}

			string paddedString = sb.ToString();
			return paddedString;
		}
	}
}
